<template>
  <div class="blockMap">
    <div class="block-content">
      <div class="block-map">
        <div id="map" />
      </div>
      <collapsebox>
        <template slot="butgroup">
          <span style="float: left">{{ $t("area.Layer") }}:</span>
          <treeselect
            v-model="mapId"
            :class="{ treeps: isDisable }"
            :disabled="isDisable"
            :placeholder="$t('area.chosenLayer')"
            :max-height="300"
            :options="mapList"
            style="float: left; width: 200px"
            @input="nodeClick"
          />
        </template>
        <template v-if="featuresList.length > 0" slot="contentgroup">
          <h4>当前区块人数密度显示</h4>
          <div>
            <div v-for="item in featuresList" :key="item.id" class="rowInfo">
              {{ item.properties.name }}
              <div
                class="blockbg"
                :style="{color:'#fff',
                         background:
                           item.curColor
                             ? item.curColor
                             : 'rgba(27, 27, 24, 0.44)'
                }"
              />{{ item.perNum }}

              <!-- {{ blockList.properties.name }}   curColor{{ blockList.properties.fencetype }} -->
            </div>
          </div>
          <div>
            <h4>人数颜色区块示意图</h4>
            <div>
              <div v-for="item in fencePeopleList" :key="item.id" class="rowInfo">
                <div
                  class="blockbg"
                  :style="{color:'#fff',
                           background:
                             item.colora
                               ? item.colora
                               : 'rgba(27, 27, 24, 0.44)'
                  }"
                />{{ item.min }}~{{ item.max }}

              <!-- {{ blockList.properties.name }}   curColor{{ blockList.properties.fencetype }} -->
              </div>
            </div>
          </div>
        </template>
      </collapsebox>
      <!-- <div class="block-map-right" /> -->
    </div>
  </div>
</template>

<script>
import CollapseCardBox from '../../components/CollapseCardBox/collapsebox.vue'
import { Draw, Modify, Snap, Select, Translate } from 'ol/interaction.js'
import { Circle, LineString, Point, Polygon } from 'ol/geom.js'
import { createRegularPolygon, createBox } from 'ol/interaction/Draw.js'
import { altKeyOnly, click, pointerMove } from 'ol/events/condition'
import { Image } from 'ol/layer.js'
import { ImageStatic } from 'ol/source.js'
import Overlay from 'ol/Overlay'
import { Projection } from 'ol/proj.js'
import { webSockUrl, baseUrl } from '@/utils/global'
import Feature from 'ol/Feature'
import {
  Style,
  Icon,
  Text,
  Fill,
  Stroke,
  Circle as CircleStyle
} from 'ol/style'
import { getLength } from 'ol/sphere'
import {
  sendThis,
  Load_Map,
  _iMap,
  _TransPixel,
  TagStyle,
  _Style,
  updateOverlayPosition,
  FenceStyle,
  _TransMetric,
  _TransMetric2,
  _TransMetric3,
  _TransMetricFence,
  _dPR,
  Load_Fence,
  FenceSource,
  Load_Fence2,
  FenceSource2
} from '@/utils/historyMap.js'
import { getMapTree, getMap } from '@/api/location'
import { GeoJSON } from 'ol/format.js'
import {
  fenceOneInfo,
  addFence,
  deleteFence
} from '@/api/system/historyDisplayInfo.js'
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getToken } from '@/utils/auth'
import { Vector as VectorSource } from 'ol/source.js'
import { Vector as VectorLayer } from 'ol/layer.js'

import {
  Circle as CircleFeature
} from 'ol/geom'
export default {
  components: {
    collapsebox: CollapseCardBox,
    Treeselect
  },
  filters: {
    getColor(val, idx, options) {
      if (options.length) {
        for (let i = 0; i < options.length; i++) {
          var strNum = parseFloat(val)
          if (strNum <= options[i].max && strNum >= options[i].min) {
          //  this.changePeaple(this.fencePeopleList[i].colora)
            return options[i].colora
          }
        }
      }
      return 'black'
    }
  },
  data() {
    return {
      featuresList: [],
      bLockEx: true,
      systemID: null,
      ws: null,
      mapName: null,
      _Select: null,
      modify: null,
      TagSource: null,
      options: [],
      mapList: [],
      mapId: null,
      isDisable: false,

      fencePeopleList: [
        {
          colorId: 'gray',
          max: 20,
          min: 0,
          // max: 1,
          // min: 0,
          color: 'gray',
          colora: 'rgba(204, 210, 202, 1)'
        },
        {
          colorId: 'pink',
          // max: 3,
          // min: 2,
          max: 40,
          min: 21,
          color: 'pink',
          colora: 'rgba(234, 157, 221, 1)'
        },
        {
          colorId: 'green',
          max: 60,
          min: 41,
          color: 'green',
          colora: 'rgba(122, 244, 103, 1)'
        },
        {
          colorId: 'yellow',
          max: 80,
          min: 61,
          color: 'yellow',
          colora: 'rgba(248, 239, 74, 1)'
        },
        {
          colorId: 'red',
          max: 100,
          min: 81,
          color: 'red',
          colora: 'rgba(245, 41, 13, 1)'
        }
      ]
    }
  },

  mounted() {
    this.initMap()
    this.webSocketPosition()
    // this.fenceModify_init(this.featuresList)
  },
  beforeDestroy() {
    this.ws.close()
  },
  methods: {
    initMap() {
      getMapTree().then(res => {
        if (res.code == 200) {
          this.mapList = res.data
          if (res.data && res.data.length > 0) {
            this.mapId = res.data[0].id
          }
          sendThis(this)
        }
      })
    },
    nodeClick() {
      const self = this
      if (
        self.mapId === '' ||
        self.mapId === undefined ||
        self.mapId === null
      ) {
        self.radius = null
        if (self._Select != null) {
          _iMap.removeInteraction(self._Select)
        }
        if (self.modify != null) {
          _iMap.removeInteraction(self.modify)
        }
        if (self.draw != null) {
          _iMap.removeInteraction(self.draw)
        }

        return
      }
      getMap(self.mapId).then(res => {
        const RES = self.responseUse(res)
        if (RES != undefined) {
          $('#map').empty()
          self.mapName = RES.mapName
          Load_Map(
            baseUrl + '/file' + RES.mapPath,
            RES.mapActualX,
            RES.mapActualY,
            RES.mapPixelX,
            RES.mapPixelY,
            RES.mapPixelX / RES.mapActualX,
            [RES.mapOriginX, RES.mapOriginY],
            false
          )

          this.loadLayer()
          // Load_Fence(self.mapId)
          Load_Fence2()
          const param = JSON.stringify({
            key: this.systemID,
            layerId: this.mapId
          })
          this.webSocketOnSend(param)

          //   Load_Fence2()
          // this.fenceModify_init()
          //   self.createMeasureTooltip2()
        }
      })
    },

    fenceModify_init(fenceData) {
      var format = new GeoJSON()
      this.featuresList = []
      this.featuresList = fenceData
      const res = {}
      res.data = this.featuresList
      const self = this

      for (let i = 0; i < res.data.length; i++) {
        if (res.data[i].mark == undefined || res.data[i].mark == 'other') {
          var newFeatures = format.readFeatures(res.data[i])
          newFeatures.forEach(function(f) {
            if (f.get('fencetype') != 'layer' && f.get('fencetype') != 'temporary') {
              var coord = f.getGeometry().getCoordinates()
              f.getGeometry().setCoordinates(_TransPixel(coord))
              f.setId(f.get('id'))
              FenceSource2.addFeature(f)
            }
            const curColor = self.getPeopleColor(res.data[i].perNum)
            res.data[i].curColor = curColor
            res.data[i].properties.curColor = curColor
            self.changePeaple(f.get('id'), curColor)
          })
        } else {
          const geometryData = res.data[i]
          const circleFeature = new Feature({
            geometry: new CircleFeature(_TransPixel(geometryData.geometry.coordinates[0][0]), _dPR * geometryData.geometry.coordinates[0][1])
          })
          circleFeature.setId(geometryData.id)
          circleFeature.properties = geometryData.properties
          circleFeature.coorRadiu = geometryData.geometry.coordinates[0][1]
          circleFeature.dotOrigin = geometryData.geometry.coordinates[0][0]
          circleFeature.set('name', geometryData.properties.name)
          circleFeature.set('fillColor', geometryData.properties.fillColor)
          circleFeature.set('frameColor', geometryData.properties.frameColor)
          FenceSource2.addFeature(circleFeature)
          const curColor = self.getPeopleColor(geometryData.perNum)
          geometryData.curColor = curColor
          geometryData.properties.curColor = curColor
          self.changePeaple(geometryData.id, curColor)
        }
      }
    },
    // 更改颜色值

    changePeaple(fenceId, colora) {
      const self = this
      const currentFeature = FenceSource2.getFeatureById(fenceId)
      // if (self.color1 == null) self.color1 = 'rgba(165,42,42,0.1)'
      // if (self.color2 == null) self.color2 = 'rgba(165,42,42)'
      const name = currentFeature.get('name')
      // console.log(currentFeature, fenceId)

      self.fenceColor = colora
      currentFeature.setStyle(
        new Style({
          fill: new Fill({
            color: colora
          }),
          stroke: new Stroke({
            lineDash: [1, 2, 3, 4, 5, 6],
            color: colora,
            width: 2
          }),
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: '#FF0000'
            })
          }),
          text: new Text({
            text: name,
            font: 'bold 14px Arial',
            textAlign: 'center',
            textBaseline: 'middle',
            offsetX: 0,
            offsetY: 0,
            fill: new Fill({
              color: '#FF0000'
            }),
            stroke: new Stroke({
              color: '#fff',
              width: 3
            })
          })
        })
      )
    },

    // 传入人数改变颜色
    getPeopleColor(people) {
      let curcolors = 'black'
      for (let i = 0; i < this.fencePeopleList.length; i++) {
        var strNum = parseFloat(people)
        if (strNum >= this.fencePeopleList[i].min && strNum <= this.fencePeopleList[i].max) {
          curcolors = this.fencePeopleList[i].colora
          return curcolors
        }
      }

      return curcolors
    },

    webSocketPosition() {
      const self = this
      self.systemID = new Date().getTime().toString()
      var param = JSON.stringify({
        register: self.systemID
      })
      if ('WebSocket' in window) {
        // self.ws = new WebSocket(webSockUrl)
        // console.log('token', getToken())
        const kkkk = 'Bearer ' + getToken()
        const url = 'ws://192.168.3.162:8080/socket/websocket/socketServer.do'
        self.ws = new WebSocket(webSockUrl)
        self.ws.onopen = function() {
          self.webSocketOnSend(param)
          console.log('数据发送中...')
        }
        self.ws.onmessage = function(evt) {
          self.getMessage(evt.data)
        }
        self.ws.onclose = function(res) {
          console.log('连接已关闭', res)
        }
        self.ws.onerror = function(err) {
          console.log('连接错误', err)
        }
      } else {
        console.log('您的浏览器不支持WebSocket!')
      }
    },
    webSocketOnSend(data) {
      const self = this
      if (self.ws.readyState === 1) {
        self.ws.send(data)
      }
    },
    getMessage(el) {
      const self = this

      const result = $.parseJSON(el)
      if (result.message === 'handshake') {
        console.log('握手初次')
      } else if (result.message === 'Point') {
        if (self.bLockEx) {
          self.bLockEx = false
          const format = new GeoJSON()
          this.fenceModify_init(result.fenceData)
          const newFeatures = format.readFeatures(result.data)
          newFeatures.forEach(function(f) {
            const coords = _TransPixel(f.getGeometry().getCoordinates())
            const tag = self.TagSource.getFeatureById(f.get('resourceId'))
            if (tag != null) {
              if (
                tag.get('pos_x') - 0.3 > f.get('pos_x') ||
                tag.get('pos_x') + 0.3 < f.get('pos_x') ||
                tag.get('pos_y') - 0.3 > f.get('pos_y') ||
                tag.get('pos_y') + 0.3 < f.get('pos_y')
              ) {
                tag.set('pos_x', f.get('pos_x'))
                tag.set('pos_y', f.get('pos_y'))
                tag.set('axis', f.get('axis'))
                tag.getGeometry().setCoordinates(coords)
                // updateOverPopupPosition(tag, coords)
              }
            } else {
              f.getGeometry().setCoordinates(coords)
              f.setId(f.get('resourceId'))
              f.set('visible', true)
              self.TagSource.addFeature(f)
              self.options.push({
                label: f.get('itemname'),
                value: f.get('resourceId')
              })
            }
          })

          self.bLockEx = true
        }
      }
    },
    loadLayer() {
      if (this.TagSource != null) {
        this.TagSource.clear()
      }
      this.TagSource = new VectorSource({
        wrapX: false
      })
      this.TagLayer = new VectorLayer({
        source: this.TagSource,
        zIndex: 99,
        style: function(feature) {
          return TagStyle(feature, 0)
        }
      })
      _iMap.addLayer(this.TagLayer)
    },
    choseBox() {
      this._Select = new Select({
        condition: click
      })
      _iMap.addInteraction(this._Select)
      this.modify = new Modify({
        features: this._Select.getFeatures()
      })
    },
    // 添加交互
    addInteraction() {
      this._Select = new Select({ condition: click })
      _iMap.addInteraction(this._Select)
      const self = this
      new Modify({
        features: self._Select.getFeatures()
      })
    }

  }
}
</script>

<style scoped>
.blockMap {
  height: 100%;
}
.block-content {
  height: 100%;
  display: flex;
}
#map {
  width: 100%;
  height: 100%;
}
.block-map {
  flex: 1;
}
.block-map-right {
  width: 300px;
}
.blockbg {
  width: 30px;
  height: 20px;
}
.rowInfo {
  display: flex;
  margin: 10px;
}
</style>
